//获取叶子节点的深度
import { deepClone, nanoid10 } from "../../../tools/Tools";
import { createCellPos } from "../Tools/index";
import { updateToolBarState } from "./GridHook";
export default class HeaderService {
    context;
    headerLevelData;
    constructor(context) {
        this.context = context;
    }
    get data() {
        return this.headerLevelData.data;
    }
    get lastHeader() {
        return this.headerLevelData.lastHeader;
    }
    get headerColumn() {
        return this.headerLevelData.headerColumn;
    }
    get headJson() {
        return this.headerLevelData.headJson;
    }
    destroy() {
        this.context = null;
    }
    headerCompute(headJson, isRefresh = true, isRefreshCellsMeta = false) {
        const { levelData, computerLevelData, headerData } = this.countHeader(headJson);
        const lastHeader = levelData[levelData.length - 1].length - 1;
        // const headerColumn = this.getHeaderColumn(headerData);
        const headerColumn = this.getHeaderColumn(headerData);
        if (!this.headerLevelData) {
            this.headerLevelData = {
                data: levelData,
                computerLevelData,
                lastHeader,
                headerColumn,
                headJson,
            };
        }
        else {
            this.headerLevelData.data = levelData;
            this.headerLevelData.computerLevelData = computerLevelData;
            this.headerLevelData.lastHeader = lastHeader;
            this.headerLevelData.headerColumn = headerColumn;
            this.headerLevelData.headJson = headJson;
        }
        if (isRefresh && this.context.hot) {
            //重置所有列的配置
            // this.context.gridService.resetAllCellMetaConfig();
            // this.context.hot.render();
            this.context.gridService.hiddenColumnAndRow();
        }
        if (isRefreshCellsMeta && this.context.hot) {
            //优:保持context持有的data保持数据同步，因为gridHooks中会用到
            this.context.hot.updateData(this.context.data);
        }
    }
    /**
     * 判断是否点击的父表头
     */
    isParentHeader(coords) {
        const { row, col } = coords;
        if (row < 0) {
            const header = this.getHeaderByCellPos(coords);
            return header && header.type === "title";
        }
        return false;
    }
    /**
     * 根据坐标，获取复合表头信息（性能高）On
     */
    getHeaderByCellPos(coords) {
        const { row, col } = coords;
        const computedLevelData = this.headerLevelData.computerLevelData;
        //表头数据
        if (row < 0) {
            const treeHeaderRowIndex = row + computedLevelData.length;
            return computedLevelData[treeHeaderRowIndex][col];
        }
        return null;
    }
    /**
     * 计算返回数据
     */
    headerComputeData(headJson) {
        const { levelData, computerLevelData, headerData } = this.countHeader(headJson);
        const lastHeader = levelData[levelData.length - 1].length - 1;
        const headerColumn = this.getHeaderColumn(headerData);
        return {
            data: levelData,
            computerLevelData,
            lastHeader,
            headerColumn,
            headJson,
        };
    }
    /**
     * 获取关键字段列
     */
    getKeywordColumnIndex() {
        //TODO 如果是直接在父表头上设计config，子表头是否继承。目前操作方式需要直接在子表头上设置。
        // console.log(this.headerColumn);
        const result = [];
        this.headerColumn.forEach((item, index) => {
            const config = item.config;
            if (config.keyword) {
                result.push(index);
            }
        });
        return result;
    }
    /**
     * 转换城后需要的数据结构
     */
    toServerLevelData(jsonData, tId, type) {
        const listLevelData = [];
        let leafCount = -1;
        const _t = this;
        const columnsMap = this.getAllHeaderMap();
        columnsMap.unshift("key"); //补key
        columnsMap.push("config");
        function findNode(listData, pId, level) {
            for (let i = 0; i < listData.length; i++) {
                const node = listData[i];
                // //保存到数据库重置guid
                // if (node.key.includes("config")) {
                //   node.key = `${nanoid10()}-config`;
                // } else if (node.key.includes("key")) {
                //   node.key = `${nanoid10()}-key`;
                // } else {
                //   node.key = nanoid10();
                // }
                if (node.children) {
                    ++level;
                    findNode(node.children, node.key, level);
                }
                else {
                    ++leafCount;
                }
                const config = node.config;
                const excludeConfig = _t.context.excludeConfigToServer(deepClone(node.config));
                let cmap = node.children ? "" : columnsMap[leafCount];
                let cmapFormat = "";
                cmapFormat = cmap && typeof cmap === "string" ? cmap.trim() : cmap;
                if (cmapFormat !== undefined && typeof cmapFormat === "string") {
                    cmapFormat = cmapFormat.replaceAll("'", "");
                }
                let labelFormat = node.label;
                if (labelFormat !== undefined && typeof labelFormat === "string") {
                    labelFormat = labelFormat.replaceAll("'", "");
                }
                if (pId && type === "zl") {
                    pId.includes("-zl") ? (pId = pId) : (pId = pId + "-zl");
                }
                //列级别config过滤
                let columnDataDao = {
                    cid: type === "zl" ? node.key + "-zl" : node.key,
                    label: labelFormat,
                    pid: pId,
                    tid: tId,
                    cov: i,
                    lov: node.children ? -1 : leafCount,
                    level,
                    ish: node.children ? 0 : 1,
                    keyword: config["keyword"] ? 1 : 0,
                    config: JSON.stringify(excludeConfig),
                    cmap: cmapFormat,
                    formula: config["formula"] || "",
                    formulaState: config["formulaState"] || "",
                    isDynamic: config["isDynamic"] || 0,
                };
                listLevelData.push(columnDataDao);
            }
        }
        findNode(jsonData, "", 0);
        return listLevelData;
    }
    //TODO 待优化
    levelDataToJsonData(designColumns) {
        const jsonTreeData = [];
        function deepLevelData(node, pid) {
            for (let i = 0; i < designColumns.length; i++) {
                const columnData = designColumns[i];
                if (node.key === columnData.pid) {
                    const childNode = {
                        key: columnData.cid,
                        label: columnData.label,
                        config: JSON.parse(columnData.config),
                    };
                    if (node["children"]) {
                        node.children.push(childNode);
                    }
                    else {
                        node.children = [];
                        node.children.push(childNode);
                    }
                    deepLevelData(childNode, columnData.cid);
                }
            }
        }
        for (let i = 0; i < designColumns.length; i++) {
            const columnData = designColumns[i];
            if (columnData.pid === "") {
                const childNode = {
                    key: columnData.cid,
                    label: columnData.label,
                    config: JSON.parse(columnData.config),
                };
                jsonTreeData.push(childNode);
            }
        }
        for (let i = 0; i < jsonTreeData.length; i++) {
            const topNode = jsonTreeData[i];
            deepLevelData(topNode, topNode.key);
        }
        return jsonTreeData;
    }
    /**
     * 获取所列顶级头部的节点key
     */
    getTopHeaderKey() {
        return this.headJson.map((node) => {
            return node.key;
        });
    }
    /**
     * 根据key获取顶级头部列的索引
     */
    getTopHeaderIndexByKey(key) {
        return this.getTopHeaderKey().indexOf(key);
    }
    /**
     * 过滤出所选列中的顶部头部
     */
    getTopHeaderKeyAndIndexBySelectedKeys(selectedKeys) {
        const topHeaderKey = this.getTopHeaderKey();
        const result = [];
        for (let i = 0; i < selectedKeys.length; i++) {
            const key = selectedKeys[i];
            if (topHeaderKey.includes(key)) {
                result.push({
                    key,
                    index: this.getTopHeaderIndexByKey(key),
                });
            }
        }
        return result;
    }
    /**
     * 获取需要移动列的计算数据
     * @param direction
     */
    getMoveColumns = (direction) => {
        const computedMovesColumns = [];
        //获取当前所选表头的keys
        const selectedKeys = this.getNodeKeyBySelected();
        //过滤出所选列中的顶部头部
        const matchTopLevelHeaderKeyAndIndex = this.getTopHeaderKeyAndIndexBySelectedKeys(selectedKeys);
        //如果没有匹配到顶级头部，则不需要移动
        if (matchTopLevelHeaderKeyAndIndex.length < 1) {
            this.context.menuToolRef.current.showErrorNotify("请选择顶级表头进行操作");
            return { computedMovesColumns };
        }
        if (matchTopLevelHeaderKeyAndIndex.length > 1) {
            this.context.menuToolRef.current.showErrorNotify("请选择单个顶级表头进行操作");
            return { computedMovesColumns };
        }
        const startCol = matchTopLevelHeaderKeyAndIndex[0];
        const endCol = matchTopLevelHeaderKeyAndIndex[matchTopLevelHeaderKeyAndIndex.length - 1];
        //左边界
        const leftEdgeCol = 1;
        //右边界
        const rightEdgeCol = this.getTopHeaderKey().length - 2;
        //如果队头行为1，则整个range不需要在移动 , 或者队尾行为最后一行，则整个range不需要在移动
        if (startCol.index === leftEdgeCol && direction === "left") {
            return { computedMovesColumns };
        }
        if (endCol.index === rightEdgeCol && direction === "right") {
            return { computedMovesColumns };
        }
        if (direction === "left") {
            for (let j = 0; j < matchTopLevelHeaderKeyAndIndex.length; j++) {
                const coords = matchTopLevelHeaderKeyAndIndex[j];
                const { key, index } = coords;
                if (index === 0) {
                    continue;
                }
                computedMovesColumns.push({
                    index,
                    target: index - 1,
                });
            }
        }
        else {
            for (let j = matchTopLevelHeaderKeyAndIndex.length - 1; j >= 0; j--) {
                const coords = matchTopLevelHeaderKeyAndIndex[j];
                const { key, index } = coords;
                if (index === 0) {
                    continue;
                }
                computedMovesColumns.push({
                    index,
                    target: index + 1,
                });
            }
        }
        return {
            computedMovesColumns,
            matchSelectTopHeader: matchTopLevelHeaderKeyAndIndex,
        };
    };
    /**
     * 列移动根据列移动计算后的数据
     */
    moveColumnsByComputedMovesColumns = (computedMovesColumns, direction) => {
        this.context.gridService.getSyncHyperData();
        const { headJson } = this;
        const newHeadJson = [...headJson];
        const computedAfterMoveRange = [];
        const sheetId = this.context.hyper.getSheetId("main");
        for (let i = 0; i < computedMovesColumns.length; i++) {
            const { index, target } = computedMovesColumns[i];
            const sourceNode = newHeadJson[index];
            const targetNode = newHeadJson[target];
            //获取source column 的叶子节点范围
            const sourceHeaderColumn = this.getColumnIndexByParentNode(sourceNode);
            const targetHeaderColumn = this.getColumnIndexByParentNode(targetNode);
            //执行交换列
            const temp = sourceNode;
            newHeadJson[index] = targetNode;
            newHeadJson[target] = temp;
            console.log(sourceHeaderColumn);
            console.log(targetHeaderColumn);
            //移动多列数据到目标列
            if (direction === "left") {
                // visual 移动方案
                this.context.manualColumnMovePlugin.moveColumns(sourceHeaderColumn, targetHeaderColumn[0]);
            }
            else {
                // visual 移动方案
                const targetLastIndex = targetHeaderColumn[targetHeaderColumn.length - 1];
                const targetIndex = targetLastIndex - (sourceHeaderColumn.length - 1);
                console.log(targetIndex);
                this.context.manualColumnMovePlugin.moveColumns(sourceHeaderColumn, targetIndex);
            }
            console.log(this.context.hyper.getAllSheetsSerialized());
            this.context.hyper.moveColumns(sheetId, sourceHeaderColumn[0], sourceHeaderColumn.length, direction === "left"
                ? targetHeaderColumn[0]
                : targetHeaderColumn[0] + targetHeaderColumn.length);
            console.log(this.context.hyper.getAllSheetsSerialized());
            sourceHeaderColumn.forEach((item, index) => {
                if (direction === "left") {
                    computedAfterMoveRange.push(item - targetHeaderColumn.length);
                }
                else {
                    computedAfterMoveRange.push(item + targetHeaderColumn.length);
                }
            });
        }
        //重新刷cellMeta;
        this.context.gridService.convertVisualIndexToPhysicalIndex();
        //移动复合表头，并重算
        // this.headerCompute(newHeadJson, true);
        return {
            gridData: {
                header: newHeadJson,
                // data: this.context.data,  // visual移动方案
                data: this.context.hyper.getAllSheetsSerialized()["main"],
                cellsMeta: this.context.cellMetaData,
                tableConfig: this.context.tableConfig,
            },
            computedAfterMoveRange,
        };
    };
    getNodeIndexByGridDataKey = (keys, headerComputeData) => {
        let matchKeyLevelData = null;
        let computeLevelData = headerComputeData.computerLevelData;
        let countLevelLen = computeLevelData.length;
        for (let i = 0; i < computeLevelData.length; i++) {
            const levelData = computeLevelData[i];
            if (!levelData) {
                continue;
            }
            matchKeyLevelData = levelData.find((item) => {
                return item && item.key === keys;
            });
            if (matchKeyLevelData) {
                break;
            }
        }
        if (matchKeyLevelData) {
            const index = matchKeyLevelData.index;
            const [row, col] = index.split("_");
            return {
                coords: {
                    row: parseInt(row) - countLevelLen,
                    col: parseInt(col),
                },
                levelData: matchKeyLevelData,
            };
        }
        return null;
    };
    //根据key获取节点的行列位置
    getNodeIndexByKey = (keys) => {
        let matchKeyLevelData = null;
        let computeLevelData = this.headerLevelData.computerLevelData;
        let countLevelLen = computeLevelData.length;
        for (let i = 0; i < computeLevelData.length; i++) {
            const levelData = computeLevelData[i];
            if (!levelData) {
                continue;
            }
            matchKeyLevelData = levelData.find((item) => {
                return item && item.key === keys;
            });
            if (matchKeyLevelData) {
                break;
            }
        }
        if (matchKeyLevelData) {
            const index = matchKeyLevelData.index;
            const [row, col] = index.split("_");
            return {
                coords: {
                    row: parseInt(row) - countLevelLen,
                    col: parseInt(col),
                },
                levelData: matchKeyLevelData,
            };
        }
        return null;
    };
    /**
     *
     * @param headerRange [起始列，结束列，起始行，结束行] nestHeader插件支持
     */
    selectHeaderByIndex(headerRange, newColumnKey) {
        const hot = this.context.hot;
        //从源码中找到了这个方法，但是没有找到对应的api文档
        const selection = hot.selection;
        // selection.selectColumns(8, 9, -2);
        selection.selectColumns(...headerRange);
        const coords = selection.getSelectedRange().ranges[0].from;
        this.context.setState({
            currentRecord: {
                coords,
                key: newColumnKey,
            },
        });
        updateToolBarState(coords, newColumnKey, this.context);
    }
    /**
     * 根据key选中节点, 操作dom的方式 , 不会触发selectionChange事件 , 只能再通过getSelectedNode获取选中的节点
     * 因为handson本身不支持多范围表头选中.这里需要自己处理一下
     * 废弃
     */
    selectNodeByKeyByDom(keys) {
        //清空所有选择样式，清空了样式后只要触发handson的重绘。内部会记录这个状态导致手动添加的样式失效.
        this.context.hot.deselectCell();
        //Mark 自己清空样式无效。因为handson内部会记录上次的选中状态，并且根据状态重新渲染。
        // this.clearHeaderActiveStyle();
        //获取表头dom容器
        const gridContainer = this.context.containerRef.current;
        //匹配到的叶子节点
        const matchHeaderColumn = [];
        //需要标注的样式dom
        const highlightDomKey = [];
        //生成selectCells参数
        const cellsSelection = [];
        // 选择后更新state，TODO 选择状态目前不支持多key，默认选择第一个
        const df_key = keys[0];
        let df_node;
        //递归选择列头
        for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            this.recursionNodeByKey(key, this.headJson, (node) => {
                if (node.key === df_key) {
                    df_node = node;
                }
                highlightDomKey.push(node.key);
                if (node.header) {
                    matchHeaderColumn.push(node.key);
                }
                // console.log(node);
            });
        }
        const startRow = 1;
        const endRow = this.context.data.length - 1;
        //获取匹配到的叶子节点的列索引
        matchHeaderColumn.forEach((item, index) => {
            for (let i = 0; i < this.headerColumn.length; i++) {
                const column = this.headerColumn[i];
                if (column.key === item) {
                    cellsSelection.push([startRow, i, endRow, i]);
                }
            }
        });
        // 选择列头下的表信息 this.context.hot.selectColumns()不支持多选, 所以需要用selectCells替代
        // 选择表体会导致失去焦点时，选择样式不同步. 有的时候还会造成表头选择失效 暂时不选择表体
        // this.context.hot.selectCells(cellsSelection);
        //mark: 必须要保证顺序再selectCells后面,否则selectCells会清空样式
        highlightDomKey.forEach((key) => {
            if (gridContainer) {
                const master_dom = gridContainer.querySelector(`.ht_master [key="${key}"]`);
                const clone_dom = gridContainer.querySelector(`.ht_clone_top [key="${key}"]`);
                if (master_dom && clone_dom) {
                    master_dom.classList.add("ht__active_highlight");
                    clone_dom.classList.add("ht__active_highlight");
                }
            }
        });
    }
    /**
     * 清空表头样式
     */
    clearHeaderActiveStyle() {
        const gridContainer = this.context.containerRef.current;
        if (gridContainer) {
            const master_dom = gridContainer.querySelectorAll(`.ht_master .ht__active_highlight`);
            const clone_dom = gridContainer.querySelectorAll(`.ht_clone_top .ht__active_highlight`);
            master_dom.forEach((item) => {
                item.classList.remove("ht__active_highlight");
            });
            clone_dom.forEach((item) => {
                item.classList.remove("ht__active_highlight");
            });
        }
    }
    /**
     * 根据指定key递归子节点,并提供回调
     */
    recursionNodeByKey(key, data, callback) {
        const matchNode = this.findNodeByKey(key);
        if (!matchNode) {
            return;
        }
        //如果没有子节点,直接返回
        if (matchNode && !matchNode.children) {
            matchNode.header = true;
            callback(matchNode);
            return;
        }
        else {
            callback(matchNode);
        }
        function findNodeByKeyIteration(key, data) {
            for (let i = 0; i < data.length; i++) {
                const dataItem = data[i];
                if (dataItem.children) {
                    findNodeByKeyIteration(key, dataItem.children);
                    callback(dataItem);
                }
                else {
                    dataItem.header = true;
                    callback(dataItem);
                }
            }
        }
        findNodeByKeyIteration(key, matchNode.children);
        return matchNode;
    }
    /**
     * 根据key查询节点
     * @param key
     * @param data
     * @param pNode
     */
    findNodeByKeyAndParent(key, data, pNode) {
        let nodeInfo = null;
        function findNodeByKeyIteration(key, data, pNode) {
            for (let i = 0; i < data.length; i++) {
                const dataItem = data[i];
                if (dataItem.children && nodeInfo === null) {
                    findNodeByKeyIteration(key, dataItem.children, dataItem);
                }
                if (dataItem.key + "" === key + "") {
                    nodeInfo = {
                        pNode,
                        config: dataItem["config"],
                        index: i,
                    };
                }
            }
        }
        findNodeByKeyIteration(key, data, pNode);
        return nodeInfo;
    }
    /**
     * 根据key查询节点
     * @param key
     * @param data
     * @param pNode
     */
    findNodeByKey(key, data) {
        let matchNode = null;
        if (!data) {
            data = this.headJson;
        }
        function findNodeByKeyIteration(key, data) {
            for (let i = 0; i < data.length; i++) {
                const dataItem = data[i];
                if (dataItem.key + "" === key + "") {
                    matchNode = dataItem;
                }
                if (dataItem.children && matchNode === null) {
                    findNodeByKeyIteration(key, dataItem.children);
                }
                if (dataItem.key + "" === key + "") {
                    matchNode = dataItem;
                }
            }
        }
        findNodeByKeyIteration(key, data);
        return matchNode;
    }
    /**
     * 根据key修改节点信息
     * @param key
     * @param data
     * @param param
     * @param isConfig ， 是否仅操作config配置项
     * @param remove
     */
    updateNodeByKey(key, data, param, isConfig, remove) {
        let _this = this;
        function findNodeByKeyIteration(key, data) {
            for (let i = 0; i < data.length; i++) {
                let dataItem = data[i];
                if (dataItem.children) {
                    if (dataItem.key + "" === key + "") {
                        data[i] = _this.updateConfig(dataItem, param, isConfig, remove);
                        //兼容老写法
                        if (!isConfig) {
                            data[i].label = param.label;
                        }
                    }
                    else {
                        findNodeByKeyIteration(key, dataItem.children);
                    }
                }
                if (dataItem.key + "" === key + "") {
                    data[i] = _this.updateConfig(dataItem, param, isConfig, remove);
                    //兼容老写法
                    if (!isConfig) {
                        data[i].label = param.label;
                    }
                }
            }
        }
        findNodeByKeyIteration(key, data);
        return data;
    }
    updateConfig(dataItem, param, isConfig, remove) {
        if (remove && remove.length > 0) {
            remove.forEach((key) => {
                if (isConfig) {
                    delete dataItem.config[key];
                }
                else {
                    delete dataItem[key];
                }
            });
        }
        if (isConfig) {
            dataItem.config = { ...dataItem.config, ...param };
        }
        else {
            dataItem = { ...dataItem, ...param };
        }
        return dataItem;
    }
    /**
     * 修改节点信息后进行表头重算
     * isConfig , 是否修改config中的配置项
     * isUpdateConfig 是否更新header配置,默认是true更新
     */
    updateNodeByKeyAndRefresh(configPrams, key, isConfig, isUpdateConfig = true) {
        if (!key) {
            console.error("未检测到key值，不是头部节点");
            return;
        }
        let update_header;
        const lastConfig = this.findNodeByKey(key, this.headJson) || {};
        if (isConfig) {
            lastConfig.config = { ...lastConfig.config, ...configPrams };
            update_header = this.updateNodeByKey(key, this.headJson, {
                ...lastConfig,
            });
        }
        else {
            update_header = this.updateNodeByKey(key, this.headJson, {
                ...lastConfig,
                ...configPrams,
            });
        }
        console.log(update_header, "update_header----");
        this.headerCompute(update_header, isUpdateConfig);
    }
    /**
     * 获取划选的header key  信息
     */
    getNodeKeyBySelected() {
        const rangeKeys = [];
        document
            .querySelectorAll(".ht_master .ht__active_highlight:not(.hidden)")
            .forEach((node) => {
            const key = node.getAttribute("key");
            rangeKeys.push(key);
        });
        return rangeKeys;
    }
    /**
     * 获取划选的header index位置
     */
    getNodeIndexBySelected() {
        const rangeIndex = [];
        this.getNodeKeyBySelected().forEach((key) => {
            this.headerColumn.forEach((item, index) => {
                if (item.key === key) {
                    rangeIndex.push(index);
                }
            });
        });
        return rangeIndex;
    }
    /**
     * 批量更新列配置根据列索引范围 ，  默认按照json树的索引更新
     */
    bathUpdateHeaderConfigByIndex(p_range, params, handle) {
        const range = p_range[0];
        const from_col = range.from.col;
        const to_col = range.to.col + 1;
        let lastUpdateHeader = this.headJson;
        for (let i = from_col; i < to_col; i++) {
            lastUpdateHeader = this.updateHeaderConfigByIndex(lastUpdateHeader, i, {
                ...params,
            });
        }
        this.headerCompute(lastUpdateHeader);
    }
    /**
     * 根据列设置索引
     * @param dataItem headerJson对象
     * @param column 要设置的列的索引号
     * @param params 设置的参数如  {width:120}
     * infoParams
     */
    updateHeaderConfigByIndex(dataItem = this.headJson, column, params = null, infoParams = null) {
        let leafCount = 0;
        let isStop = false;
        function leafIteration(parentNode, column, params, infoParams) {
            for (let i = 0; i < parentNode.length; i++) {
                const leafItem = parentNode[i];
                if (leafItem.children && !isStop) {
                    leafIteration(leafItem.children, column, params, infoParams);
                }
                else {
                    if (leafCount === column) {
                        if (infoParams) {
                            leafItem.label = infoParams.label;
                        }
                        if (params) {
                            leafItem.config = {
                                ...leafItem.config,
                                ...params,
                            };
                        }
                        isStop = true;
                    }
                    leafCount++;
                }
            }
        }
        leafIteration(dataItem, column, params, infoParams);
        return dataItem;
    }
    /**
     * 更新所有列的key信息
     */
    resetHeaderId(data) {
        const copyData = [...data];
        function findNodeByKeyIteration(headJson) {
            for (let i = 0; i < headJson.length; i++) {
                const node = headJson[i];
                if (node.children) {
                    findNodeByKeyIteration(node.children);
                }
                if (node.key.includes("config")) {
                    node.key = `${nanoid10()}-config`;
                }
                else if (node.key.includes("key")) {
                    node.key = `${nanoid10()}-key`;
                }
                else {
                    node.key = nanoid10();
                }
            }
        }
        findNodeByKeyIteration(copyData);
        return copyData;
    }
    /**
     * 获取列所有的指定config key信息
     */
    getAllHeaderMap(data) {
        let result;
        if (data) {
            result = [...data[0]];
        }
        else {
            result = this.context.hot.getDataAtRow(0);
        }
        if (result && result.length) {
            result = result.map((item) => item + ""); //兼容cmap为数字的情况
        }
        result.shift();
        result.pop();
        return result;
    }
    /**
     * 获取列配置信息根据列index
     * @param dataItem
     * @param column
     * @param params
     */
    getHeaderConfigByIndex(dataItem, column) {
        let leafCount = 0;
        let matchConfig = null;
        let isStop = false;
        function leafIteration(parentNode, column) {
            for (let i = 0; i < parentNode.length; i++) {
                const leafItem = parentNode[i];
                if (leafItem.children && !isStop) {
                    leafIteration(leafItem.children, column);
                }
                else {
                    if (leafCount === column) {
                        matchConfig = leafItem;
                        isStop = true;
                    }
                    leafCount++;
                }
            }
        }
        leafIteration(dataItem, column);
        return matchConfig;
    }
    /**
     * 获取叶子节点长度
     * @param dataItem
     */
    getLeafLength(dataItem) {
        let leafCount = 0;
        function leafIteration(parentNode) {
            for (let i = 0; i < parentNode.length; i++) {
                const leafItem = parentNode[i];
                if (leafItem.children) {
                    leafIteration(leafItem.children);
                }
                else {
                    leafCount++;
                }
            }
        }
        leafIteration(dataItem);
        return leafCount;
    }
    getHeaderColumn(dataItem) {
        let leaf_array = [];
        function leafIteration(parentNode, parentLabel) {
            for (let i = 0; i < parentNode.length; i++) {
                const leafItem = parentNode[i];
                if (parentLabel) {
                    leafItem.pathLabel = `${parentLabel}-${leafItem?.label}`;
                }
                else {
                    leafItem.pathLabel = leafItem?.label;
                }
                if (leafItem.children) {
                    leafIteration(leafItem.children, leafItem.pathLabel);
                }
                else {
                    leaf_array.push(leafItem);
                }
            }
        }
        leafIteration(dataItem);
        return leaf_array;
    }
    //根据父节点，查询一共有多少个子节点并计算出。坐在整体叶子节点中的位置
    getColumnIndexByParentNode(parentNode, TransFormHeaderData) {
        if (!TransFormHeaderData) {
            TransFormHeaderData = this.headJson;
        }
        // 1递归出所有的叶子节点
        let leafCount = 0;
        let leaf_array = []; // key array
        let leaf_index_array = [];
        function leafIteration(parentNode, type) {
            for (let i = 0; i < parentNode.length; i++) {
                const leafItem = parentNode[i];
                if (leafItem?.children) {
                    leafIteration(leafItem.children, type);
                }
                else {
                    if (type === "find") {
                        leaf_array.push(leafItem.key);
                    }
                    else {
                        if (leaf_array.indexOf(leafItem.key) > -1) {
                            leaf_index_array.push(leafCount);
                        }
                    }
                    leafCount++;
                }
            }
        }
        leafIteration([parentNode], "find");
        leafCount = 0;
        //二次递归找出序列
        leafIteration(TransFormHeaderData, "match");
        console.log("计算出来的位置:");
        console.log(leaf_index_array);
        return leaf_index_array;
    }
    //获取左侧兄弟节点的Colspan和
    getLastAddColspan(rowData, columnIndex) {
        let count = 0;
        for (let i = 0; i < rowData.length; i++) {
            if (i === columnIndex) {
                break;
            }
            else {
                if (rowData[i]) {
                    count += rowData[i].colspan;
                }
            }
        }
        return count;
    }
    /**
     * 计算头部逻辑
     * jsonData -> levelData -> ExcelData
     */
    countHeader(TransFormHeaderData) {
        //表头设计算法:
        //1. 根据数据格式解析出行总数，列总数，以及最深level层级
        // 1.1 行总数 = 最深level
        // 1.2 列总数 = 所有可操作表头字段的总数（叶子节点总数）
        // 1.3 level = 最深的叶子几点层级
        //2. 每个单元格的 colspan 和 rowspan计算
        // 2.1 colspan  =  该父节点下的所有叶子节点的数量
        // 2.2 rowspan = 将 !!叶子节点!! 对比最大level。 计算出相差数， 进行rowspan补充合并
        let columnCount = 0;
        let maxLevel = 0;
        let leaf = [];
        let headerData = JSON.parse(JSON.stringify(TransFormHeaderData));
        const _this = this;
        //3. 利深度遍历方式，根据json树形结构自动计算出每个单元格的colspan和rowspan值. 算法参考上面1，2的说明
        function countHeaderParams(headerData, level, parent, lastLabel) {
            for (let i = 0; i < headerData.length; i++) {
                const dataItem = headerData[i];
                dataItem["cmap"] = lastLabel + dataItem.label;
                if (dataItem?.children) {
                    dataItem["colspan"] = _this.getLeafLength([dataItem]);
                    dataItem["rowspan"] = 1;
                    dataItem["level"] = level;
                    dataItem["type"] = "title";
                    if (parent) {
                        dataItem["pid"] = parent.value;
                    }
                    else {
                        dataItem["pid"] = "";
                    }
                    let newLastLabel = lastLabel + dataItem.label + "-";
                    let countLevel = level + 1;
                    if (maxLevel < countLevel) {
                        maxLevel = countLevel;
                    }
                    countHeaderParams(dataItem.children, countLevel, dataItem, newLastLabel);
                }
                else {
                    columnCount++;
                    dataItem["level"] = level;
                    dataItem["colspan"] = 1;
                    dataItem["type"] = "header";
                    dataItem.config["columnIndex"] = createCellPos(columnCount - 1);
                    if (parent) {
                        dataItem["pid"] = parent.value;
                    }
                    else {
                        dataItem["pid"] = "";
                    }
                    leaf.push(dataItem);
                    // console.log("leaf");
                    // console.log(dataItem.label);
                }
            }
        }
        countHeaderParams(headerData, 1, null, "");
        //由于自动计算rowspan的方式依赖于最深level层级。所以需要先算出最深level后进行rowspan处理.
        for (let i = 0; i < leaf.length; i++) {
            const leafItem = leaf[i];
            leafItem["rowspan"] = maxLevel - leafItem.level + 1;
        }
        console.log("----------------jsonTreeData--------------------");
        console.log(headerData);
        localStorage.setItem("headerData", JSON.stringify(headerData));
        //按照level将树形结构进行平级结构转换。
        let levelData = Array.from(new Array(maxLevel || 1), () => []);
        let copy_levelData = Array.from(new Array(maxLevel || 1), () => []);
        //根据平级结构计算null的填补位置
        let computerLevelData = Array.from(new Array(maxLevel || 1), () => []);
        //将生成好的colspan 和 rowspan 转成 sheet merge 逻辑
        //按照level等级递归生成数据, level 1 为第一行， level2为第二行 .....
        function matchLevelData(headerData, level) {
            for (let i = 0; i < headerData.length; i++) {
                const headerDataItem = headerData[i];
                if (headerDataItem.children) {
                    if (headerDataItem.level === level + 1) {
                        const { children, ...other } = headerDataItem;
                        levelData[level].push({ ...other });
                    }
                    matchLevelData(headerDataItem.children, level);
                }
                else {
                    if (maxLevel === 0) {
                        levelData[0].push(headerDataItem);
                    }
                    if (headerDataItem.level === level + 1) {
                        levelData[level].push(headerDataItem);
                    }
                }
            }
        }
        //递归调用生成平级数据
        if (maxLevel === 0) {
            matchLevelData(headerData, 1);
        }
        else {
            for (let i = 0; i < maxLevel; i++) {
                matchLevelData(headerData, i);
            }
        }
        //TODO 可优化 利用levelData将数据转至成叶子节点长度的平级结构，直接操作levelData会造成数据透传混乱
        for (let i = 0; i < levelData.length; i++) {
            const rowData = levelData[i];
            for (let j = 0; j < rowData.length; j++) {
                const cellData = rowData[j];
                const columnIndex = this.getLastAddColspan(rowData, j);
                cellData["index"] = `${i}_${columnIndex}`;
                //computerLevelData[i][columnIndex] = cellData;
                copy_levelData[i][columnIndex] = cellData;
            }
        }
        //计算填补null的位置
        //算法:
        //1. colspan的计算方式为。连续相加自己左侧colspan的值. 算出自己应该所在行位置
        //2. rowspan 自动计算透传到下一个level 例如level1 第四个位置 rowspan 3   透传—>  level2 第四个位置 rowspan 2 colspan1
        for (let i = 0; i < copy_levelData.length; i++) {
            const rowData = copy_levelData[i];
            const handleLevel = i + 1;
            for (let j = 0; j < rowData.length; j++) {
                const cellData = rowData[j];
                if (!cellData) {
                    continue;
                }
                //计算左侧兄弟值colspan的合计
                const columnIndex = this.getLastAddColspan(rowData, j);
                //如果检测到本level中的元素有rowspan。则进行向下透传
                if (cellData.rowspan > 1) {
                    if (handleLevel < copy_levelData.length) {
                        const index = columnIndex;
                        copy_levelData[handleLevel].splice(index, 0, {
                            label: "null",
                            colspan: 1,
                            rowspan: cellData.rowspan - 1,
                        });
                    }
                }
                cellData["index"] = `${i}_${columnIndex}`;
                computerLevelData[i][columnIndex] = cellData;
            }
        }
        //TODO 可优化 清空empty的数据
        for (let i = 0; i < copy_levelData.length; i++) {
            const rowData = copy_levelData[i];
            for (let j = rowData.length - 1; j >= 0; j--) {
                const cellData = rowData[j];
                if (!cellData) {
                    copy_levelData[i].splice(j, 1);
                }
            }
        }
        levelData = copy_levelData;
        // console.log("----------------levelData 平级结构--------------------");
        // console.log(levelData);
        // console.log(
        //   "----------------computerLevelData 填补null后的计算--------------------"
        // );
        // console.log(computerLevelData);
        return {
            levelData,
            computerLevelData,
            headerData,
        };
    }
    getVisibleColumn() {
        let columnArr;
        // if (sessionStorage.allHeaderColumn && sessionStorage.allHeaderColumn !== 'undefined') {
        //   columnArr = JSON.parse(sessionStorage.allHeaderColumn);
        // } else {
        const headJson = this.context.dsSourceData.header;
        const headerColumn = this.getHeaderColumn(headJson);
        columnArr = headerColumn.slice(1, headerColumn.length - 1); // 去掉两个隐藏列
        if (columnArr && columnArr.length) {
            columnArr = columnArr.filter((item) => !item?.config?.isRuntime);
        }
        // if (columnArr && columnArr != "undefined") {
        //   // sessionStorage.allHeaderColumn = JSON.stringify(columnArr);
        //   if (!this.context.tableConfig) {
        //     this.context.tableConfig = {};
        //   }
        //   if (typeof this.context.tableConfig === "string") {
        //     this.context.tableConfig = JSON.parse(this.context.tableConfig);
        //   }
        //   this.context.tableConfig.allHeaderColumn = columnArr;
        // }
        //}
        return columnArr;
    }
}
